package cn.lh.pipeline;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.UUID;

import tool.StaticTools;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

public class MysqlPipeline implements Pipeline {
	
	public static int insCount;

	//有一个容器
//	DataSource ds = StaticTools.getDataSource();//直接使用即可，不用显示的配置，其会自动识别配置文件
	public void process(ResultItems resultItems, Task task) {
		//每进来一次代表一条记录
		//如果容器值达到1000，存一次数据库并将数据清空，否则将数据存入容器
		Map<String, Object> m = resultItems.getAll();
		if(!m.isEmpty()){
		String developName = m.get("developName").toString();
		String contentCategory =  m.get("contentCategory").toString();
		String type = m.get("type").toString();
		String url = m.get("url").toString();
		Object pagination = m.get("pagination").toString();
		Object order = m.get("order");
		String title = (String)m.get("title");
		Object content =  m.get("content");
		Object time = m.get("release_time");
		UUID uuid = UUID.randomUUID();  
        String str = uuid.toString();  
        // 去掉"-"符号  
        String temp = str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
			Connection conn = null;
			try {
				conn = StaticTools.getDataSource().getConnection();
				//通过正文查记录，不存在则插入该记录。插完静态变量加1
				String inssql = "select * from t_zs_zhengcetest where content=?";
				PreparedStatement ps =  conn.prepareStatement(inssql);
				ps.setString(1, content.toString());
				ResultSet rs = ps.executeQuery();
				if (rs.next()==false) {
					rs.close();
					ps.close();
					String sql = "insert into t_zs_zhengcetest(area,leixing,type,url,title,pagination,page_order,content,createdata,id) values(?,?,?,?,?,?,?,?,?,?)";
					PreparedStatement pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, developName);
					pstmt.setString(2, contentCategory);
					pstmt.setString(3, type);
					pstmt.setString(4, url);
					pstmt.setString(5, title);
					if(pagination!=null){
						pstmt.setString(6, pagination.toString());
					}else{
						pstmt.setString(6,null);
					}
					if(order!=null){
						pstmt.setString(7, order.toString());
					}else{
						pstmt.setString(7,null);
					}
					if(content!=null){
						pstmt.setString(8, content.toString());
					}else{
						pstmt.setString(8, null);
					}
					if(time!=null){
						pstmt.setString(9, time.toString());
					}else{
						pstmt.setString(9, null);
					}
					pstmt.setString(10, temp);
					pstmt.execute();
					pstmt.close();
					conn.close();
					MysqlPipeline.insCount++;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
}

